package su.msk.jet.team01.chatik.server.db;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class DatabaseResultConverter {

	public static List<Map<String, Object>> convertResults(final ResultSet data)
			throws SQLException {
		List<Map<String, Object>> table = new ArrayList<Map<String, Object>>();
		Map<String, Object> row;
		ResultSetMetaData metaData;

		if (data != null) {
			metaData = data.getMetaData();
			while (data.next()) {
				row = createRow(data, metaData);
				table.add(row);
			}
		}

		return table;
	}

	private static Map<String, Object> createRow(final ResultSet data,
			final ResultSetMetaData metaData) throws SQLException {
		int columnCount = metaData.getColumnCount();
		HashMap<String, Object> row = new HashMap<String, Object>();

		for (int i = 1; i <= columnCount; i++) {
			row.put(metaData.getColumnName(i), data.getObject(i));
		}
		return row;
	}
	
	private DatabaseResultConverter() {
		
	}
	
}
